<?php

class AdminController extends CController
{
	public $defaultAction='login';
	public $layout='admin_main';
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			array('application.filters.AdminLoginFilter -login'),
		);
	}
	
	public function actionLogin(){
		$form=new AdminLoginForm;
		if(isset($_POST['AdminLoginForm'])){
			$form->attributes=$_POST['AdminLoginForm'];
			if($form->validate()){
				$this->redirect(array('index'));			
			}
		}
		$this->render('login',array('form'=>$form));
	}
	
	public function actionIndex(){
		$this->renderPartial('index',array());
	}
	
	public function actionLeft(){
		$this->renderPartial('left',array());
	}
	
	public function actionTop(){
		$this->renderPartial('top',array());
	}
	
	public function actionRight(){
		$this->render('right',array());
	}
	
	public function actionBusiness_admin(){
		$criteria=new CDbCriteria();
		$criteria->select='business.*,areas.name as area_name,city.name as city_name,province.name as province_name,count(product.id) as product_sum';
		$criteria->join='INNER JOIN areas ON business.area=areas.code
						 INNER JOIN areas as city ON left(business.area,4)=city.code
						 INNER JOIN areas as province ON left(business.area,2)=province.code
						 LEFT JOIN product ON product.fk_business_id=business.id and product.state=0';
		$criteria->addCondition('business.state<>1');
		$criteria->group='business.id';
		$blur=true;
		if(Yii::app()->getRequest()->isPostRequest){
			if(isset($_POST['keys'])){//页面传来的搜索关键字数组
				$_GET['keys']=$_POST['keys'];
			}
		}
		if(isset($_GET['keys'])){
			if(isset($_GET['keys']['blur'])&&$_GET['keys']['blur']=='0') $blur=false;
			foreach($_GET['keys'] as $key=>$val){
				if(trim($val)=='')
					unset($_GET['keys'][$key]);
				else if($key=='recommend1'){//时间查询
					if($val==0)
						$criteria->addCondition("business.recommend1=0");
					else
						$criteria->addCondition("business.recommend1>0");
				}
				else if($key=='recommend2'){//时间查询  
					if($val==0)
						$criteria->addCondition("business.recommend2=0");
					else
						$criteria->addCondition("business.recommend2>0");
				}
				else if($key=='recommend3'){//时间查询  
					if($val==0)
						$criteria->addCondition("business.recommend3=0");
					else
						$criteria->addCondition("business.recommend3>0");
				}
				else if($key=='product_sort'){//时间查询  
					$criteria->addCondition("FIND_IN_SET('$val',business.product_sort)");
				}	
				else if($key!='blur'){//按照模糊或精确查询
					$blur?$criteria->addSearchCondition($key,$val):$criteria->addCondition("{$key}='{$val}'");
				}
			}
		}
		
		$model=Business::model();
		$command=$model->getCommandBuilder();//因group by 查询准确记录数量
		$sql="select count(t.id) from( select business.id FROM business";
		$sql=$command->applyJoin($sql,$criteria->join);
		$sql=$command->applyCondition($sql,$criteria->condition);
		$sql=$command->applyGroup($sql,$criteria->group).") as t";//echo $sql;
		$pages=new CPagination($model->countBySql($sql,$criteria->params));
		$pages->pageSize=Yii::app()->params['page_size']['admin_business'];
		$pages->applyLimit($criteria);

		$sort=new CSort('Business');
		$sort->defaultOrder='update_time DESC';
		$sort->attributes=array_merge($model->attributeNames(),array('product_sum','province_name'));
		$sort->applyOrder($criteria);

		$models=$model->findAll($criteria);
		
		$sorts['']='全部';
		$sorts_model=Business_sorts::model()->findAllBySql('select * from business_sorts where state=0');
		foreach($sorts_model as $val){
			$sorts[$val->code]=$val->name;
		}
		
		$this->render('business_admin',array(
			'models'=>$models,
			'pages'=>$pages,
			'sort'=>$sort,
			'product_sorts'=>$sorts
		));
	}
	
	public function actionSet_business_state()
	{
		if(isset($_POST['ids'])){
			$ids=implode(',',$_POST['ids']);
			//$sql="update business set state=1 where id in($ids)";
			//Business::model()->findAllBySql($sql);
			Business::model()->updateByPk($_POST['ids'],array('state'=>1));
			$this->redirect(array('admin/business_admin')+$_GET);
		}
		if(isset($_GET['id'])&&isset($_GET['state'])){
			Business::model()->updateByPk($_GET['id'],array('state'=>$_GET['state']));
			unset($_GET['id']);
			$this->redirect(array('admin/business_admin')+$_GET);
		}
		else
			throw new CHttpException(400,'无法获得要删除的信息ID!');
	}
	
	public function actionSet_business_recommend(){
		Business::model()->updateByPk($_GET['id'],array('recommend'.$_GET['n']=>$_GET['recommend']));
		unset($_GET['id']);
		$this->redirect(array('admin/business_admin')+$_GET);
	}
	
	public function actionProduct_admin(){
		$criteria=new CDbCriteria;
		$criteria->select='product.*,business.name as business_name,business.brand as business_brand';
		$criteria->join='INNER JOIN business ON product.fk_business_id=business.id';
		$criteria->addCondition('product.state<>1');
		$blur=true;
		if(Yii::app()->getRequest()->isPostRequest){
			if(isset($_POST['keys'])){//页面传来的搜索关键字数组
				$_GET['keys']=$_POST['keys'];
			}
		}
		if(isset($_GET['keys'])){
			if(isset($_GET['keys']['blur'])&&$_GET['keys']['blur']=='0') $blur=false;
			foreach($_GET['keys'] as $key=>$val){
				if(trim($val)=='')
					unset($_GET['keys'][$key]);
				else if($key!='blur'){//按照模糊或精确查询
					$blur?$criteria->addSearchCondition($key,$val):$criteria->addCondition("{$key}='{$val}'");
				}
			}
		}
		
		$model=Product::model();
		$pages=new CPagination($model->count($criteria));
		$pages->pageSize=Yii::app()->params['page_size']['admin_product'];
		$pages->applyLimit($criteria);

		$sort=new CSort('Product');
		$sort->defaultOrder='update_time DESC';
		$sort->attributes=array_merge($model->attributeNames(),array('business_brand','business_name'));
		$sort->applyOrder($criteria);

		$models=$model->findAll($criteria);

		$this->render('product_admin',array(
			'models'=>$models,
			'pages'=>$pages,
			'sort'=>$sort,
		));
	}
	
	public function actionSet_product_state()
	{
		if(isset($_POST['ids'])){
			$ids=implode(',',$_POST['ids']);
			//$sql="update business set state=1 where id in($ids)";
			//Business::model()->findAllBySql($sql);
			Product::model()->updateByPk($_POST['ids'],array('state'=>1));
			$this->redirect(array('admin/product_admin')+$_GET);
		}
		if(isset($_GET['id'])&&isset($_GET['state'])){
			Product::model()->updateByPk($_GET['id'],array('state'=>$_GET['state']));
			unset($_GET['id']);
			$this->redirect(array('admin/product_admin')+$_GET);
		}
		else
			throw new CHttpException(400,'无法获得要删除的信息ID!');
	}
	
	public function actionCreate_news(){
		$model=new News;
		if(isset($_POST['News']))
		{
			$model->attributes=$_POST['News'];
			if($model->save()){
				$this->redirect(array('show_news','id'=>$model->id,'mess'=>'添加成功!','ret'=>'create_news'));
			}
		}
		$this->render('news_form',array('model'=>$model,'update'=>true));
	}
	
	public function actionShow_news()
	{
		$this->render('show_news',array('model'=>$this->loadNews()));
	}
	
	public function actionNews_admin(){
		$criteria=new CDbCriteria;
		$criteria->addCondition('state=0');
		$blur=true;
		if(Yii::app()->getRequest()->isPostRequest){
			if(isset($_POST['keys'])){//页面传来的搜索关键字数组
				$_GET['keys']=$_POST['keys'];
			}
		}
		if(isset($_GET['keys'])){
			if(isset($_GET['keys']['blur'])&&$_GET['keys']['blur']=='0') $blur=false;
			foreach($_GET['keys'] as $key=>$val){
				if(trim($val)=='')
					unset($_GET['keys'][$key]);
				else if($key!='blur'){//按照模糊或精确查询
					$blur?$criteria->addSearchCondition($key,$val):$criteria->addCondition("{$key}='{$val}'");
				}
			}
		}
		
		$model=News::model();
		$pages=new CPagination($model->count($criteria));
		$pages->pageSize=Yii::app()->params['page_size']['admin_news'];
		$pages->applyLimit($criteria);

		$sort=new CSort('News');
		$sort->applyOrder($criteria);

		$models=$model->findAll($criteria);

		$this->render('news_admin',array(
			'models'=>$models,
			'pages'=>$pages,
			'sort'=>$sort,
		));
	}
	
	public function actionUpdate_news(){
		$model=$this->loadNews();
		if(isset($_POST['News']))
		{
			$model->attributes=$_POST['News'];
			if($model->save())
				$this->redirect(array('show_news','id'=>$model->id,'mess'=>'更新成功!','ret'=>'news_admin')+$_GET);
		}
		$this->render('news_form',array('model'=>$model,'update'=>false));
	}
	
	public function actionDelete_news()
	{	
		if(isset($_POST['ids'])){
			$ids=implode(',',$_POST['ids']);
			//$sql="update business set state=1 where id in($ids)";
			//Business::model()->findAllBySql($sql);
			News::model()->updateByPk($_POST['ids'],array('state'=>1));
			$this->redirect(array('admin/news_admin')+$_GET);
		}
		if(isset($_GET['id'])){
			News::model()->updateByPk($_GET['id'],array('state'=>1));
			unset($_GET['id']);
			$this->redirect(array('admin/news_admin')+$_GET);
		}
		else
			throw new CHttpException(400,'无法获得要删除的信息ID!');
	}
	
	public function actionUploadedFiles()
	{
		$state=$this->uploadfile('filedata');
		echo json_encode($state);
	}
	
	function uploadfile($inputname)
	{
		$mode=isset($_GET['mode'])?$_GET['mode']:'news';
		$mode_times="upload_{$mode}_times";
		
		$times=isset(Yii::app()->session[$mode_times])?Yii::app()->session[$mode_times]:0;
		if($times>=Yii::app()->params[$mode_times])
			return array('err'=>'一次性最多上传'.Yii::app()->params[$mode_times].'次图片,如仍需继续上传请提交信息后修改信息,或刷新本页进行上传.','msg'=>'');
		Yii::app()->session[$mode_times]=++$times;
			
		$immediate=isset($_GET['immediate'])?$_GET['immediate']:0;
		$attachdir='upload/temp/'.$mode;//上传文件保存路径，结尾不要带/
		$dirtype=1;//1:按天存入目录 2:按月存入目录 3:按扩展名存目录  建议使用按天存
		$maxattachsize=Yii::app()->params["upload_{$mode}_size"][0];//最大上传大小
		$maxsizemsg=Yii::app()->params["upload_{$mode}_size"][1];
		$upext='txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid';//上传扩展名
		$msgtype=2;//返回上传参数的格式：1，只返回url，2，返回参数数组
	
		$err = "";
		$msg = "";
		if(!isset($_FILES[$inputname]))return array('err'=>'文件域的name错误或者没选择文件','msg'=>$msg);
		$upfile=$_FILES[$inputname];
		if(!empty($upfile['error']))
		{
			switch($upfile['error'])
			{
				case '1':
					$err = '文件大小超过了php.ini定义的upload_max_filesize值';
					break;
				case '2':
					$err = '文件大小超过了HTML定义的MAX_FILE_SIZE值';
					break;
				case '3':
					$err = '文件上传不完全';
					break;
				case '4':
					$err = '无文件上传';
					break;
				case '6':
					$err = '缺少临时文件夹';
					break;
				case '7':
					$err = '写文件失败';
					break;
				case '8':
					$err = '上传被其它扩展中断';
					break;
				case '999':
				default:
					$err = '无有效错误代码';
			}
		}
		elseif(empty($upfile['tmp_name']) || $upfile['tmp_name'] == 'none')$err = '无文件上传';
		else
		{
			$temppath=$upfile['tmp_name'];
			$fileinfo=pathinfo($upfile['name']);
			$extension=$fileinfo['extension'];
			if(preg_match('/'.str_replace(',','|',$upext).'/i',$extension))
			{
				$filesize=filesize($temppath);
				if($filesize > $maxattachsize)$err='文件大小超过'.$maxsizemsg.'字节';
				else
				{
					switch($dirtype)
					{
						case 1: $attach_subdir = date('Y').'/'.date('m').'/'.date('d'); break;
						case 2: $attach_subdir = 'month_'.date('ym'); break;
						case 3: $attach_subdir = 'ext_'.$extension; break;
					}
					$attach_dir = $attachdir.'/'.$attach_subdir;
					if(!is_dir($attach_dir))
					{
						@mkdir($attach_dir, 0777,true);
						@fclose(fopen($attach_dir.'/index.htm', 'w'));
					}
				PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
				$filename=date("YmdHis").mt_rand(1000,9999).'.'.$extension;
				$target = $attach_dir.'/'.$filename;
				
				move_uploaded_file($upfile['tmp_name'],$target);
				if($immediate=='1')$target='!'.$target;
				if($msgtype==1)$msg=$target;
				else $msg=array('url'=>$target,'localname'=>$upfile['name'],'id'=>'1');//id参数固定不变，仅供演示，实际项目中可以是数据库ID
			}
		}
		else $err='上传文件扩展名必需为：'.$upext;

		@unlink($temppath);
	}
	return array('err'=>$err,'msg'=>$msg);
	}
	
	public function loadNews($id=null)
	{
		
			if($id!==null || isset($_GET['id']))
				$model=News::model()->findbyPk($id!==null ? $id : $_GET['id']);
			if($model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
}
